// 存储连接的客户端
const clients = new Set();

const wsChatUtlis = (ws, req) => {
  // 将新连接的客户端添加到集合中
  clients.add(ws);
  const clientId = generateClientId();
  // 发送欢迎消息给连接的客户端
  const params = {
    type: 0,
    wel: "欢迎来到聊天室",
    userId: clientId,
  };
  ws.send(JSON.stringify(params));
  // console.log(clientId);
  // 监听消息事件
  ws.on("message", (message) => {
    // 广播消息给所有客户端
    clients.forEach((client) => {
      if (ws !== client && client.readyState === client.OPEN) {
        client.send(message);
      }
    });
  });
  // 监听连接关闭事件
  ws.on("close", () => {
    clients.delete(ws);
    console.log(`Client disconnected: ${clientId}`);
  });

  // 监听错误事件
  ws.on("error", (error) => {
    console.error(`Client ${clientId} encountered error: ${error.message}`);
  });
};

function generateClientId() {
  return Math.random().toString(36).slice(2, 9);
}

module.exports = {
  wsChatUtlis,
};
